package com.ph.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ph.pojo.Permission;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface PermissionMapper extends BaseMapper<Permission> {
    List<Permission> findByTree(@Param("parentId") Integer parentId,
                                                @Param("roleId") Integer roleId);
    @Select("select count(id) from sys_role_permission " +
            "where rid = #{roleId} and pid = #{permissionId}")
    boolean checkPermission(@Param("roleId") Integer roleId,
                            @Param("permissionId") Integer permissionId);
    @Insert("insert into sys_role_permission" +
            " values (null,#{permissionId},#{roleId})")
    boolean addCheckPermission(@Param("roleId") Integer roleId,
                              @Param("permissionId") Integer permissionId);
    @Delete("delete from sys_role_permission where rid = #{roleId} and pid = #{permissionId}")
    boolean deleteCheckPermission(@Param("roleId") Integer roleId,
                                @Param("permissionId") Integer permissionId);

    @Delete("delete from sys_role_permission " +
            "where pid in " +
            "(" +
            "select id from sys_permission " +
            "where parent_id = #{permissionId}" +
            ")and rid = #{roleId}")
    boolean deleteParentPermission(@Param("roleId") Integer roleId
            ,@Param("permissionId") Integer permissionId);

    @Select("select id from sys_permission where parent_id = #{permissionId}")
    List<Integer> findPermissionIdsByParentId(@Param("permissionId") Integer permissionId);

    @Select("SELECT p1.* from sys_permission p1\n" +
            "LEFT JOIN sys_permission p2 on p1.id = p2.parent_id\n" +
            "LEFT JOIN sys_permission p3 on p2.id = p3.parent_id\n" +
            "where p1.parent_id = 0 and p3.id in\n" +
            "(\n" +
            "SELECT p.id from sys_user_role ur\n" +
            "LEFT JOIN sys_role_permission rp on ur.rid = rp.rid\n" +
            "LEFT JOIN sys_permission p on rp.pid = p.id\n" +
            "where ur.uid = #{userId} and rp.pid is not null\n" +
            ")\n" +
            "GROUP BY p1.id")
    List<Permission> findLevel1ByUserId(Integer userId);
}
